<template>
  <view class="safety-20 bg-#ffffff" style="min-height: 100vh">
    <view class="forms">
      <uv-index-list ref="listRef" :index-list="indexList">
        <template #header>
          <view class="px-32rpx pt-24rpx pb-12rpx">
            <view class="h-62rpx flex items-center bg-#F9F9F9 rd-200rpx box-border px-24rpx" @click="goSearch">
              <uv-icon name="search" color="#727687" size="36rpx"></uv-icon>
              <text class="text-28rpx text-#ADB0BD ml-16rpx">请输入城市名</text>
            </view>
          </view>
          <view class="pl-16rpx pt-24rpx">
            <mt-title>
              <template #title>
                <text class="text-28rpx font-bold">热门城市</text>
              </template>
            </mt-title>
            <view class="flex flex-wrap pt-24rpx">
              <view
                v-for="(son, sidx) in hotCityArr"
                :key="sidx"
                class="city-item"
                :class="{ active: modelForm.city === son.city }"
                @click="handleClick(son)"
              >
                {{ son.city }}
              </view>
            </view>
          </view>
        </template>
        <template v-for="(item, index) in itemArr" :key="index">
          <uv-index-item>
            <uv-index-anchor :text="indexList[index]"></uv-index-anchor>
            <view class="flex flex-wrap pl-16rpx">
              <view
                v-for="(son, sidx) in item"
                :key="sidx"
                class="city-item"
                :class="{ active: modelForm.city === son.city }"
                @click="handleClick(son)"
              >
                {{ son.city }}
              </view>
            </view>
          </uv-index-item>
        </template>
      </uv-index-list>
    </view>
  </view>
</template>

<script setup>
import pinyin from 'js-pinyin';
import { regiongetAppProvinceCityTree } from '@/api/common';
import useCommonStore from '@/store/common';

const commonStore = useCommonStore();

const types = ref(1); // 1 单选 2 多选
const modelForm = ref({
  provinceCode: '',
  province: '',
  cityCode: '',
  city: ''
});

const listRef = ref();
const cityArr = ref([]);
const flatCityArr = ref([]);
const hotCityArr = ref([]);
const indexList = ref([]);
const itemArr = ref([]);
function getCity() {
  regiongetAppProvinceCityTree().then((res) => {
    const list = res.data;
    cityArr.value = list;
    const result = handleTree(list);
    indexList.value = Object.keys(result).sort();
    itemArr.value = indexList.value.map((letter) => result[letter]);

    initScroll();
  });
}

function initScroll() {
  if (modelForm.value.city) {
    const letter = pinyin.getFullChars(modelForm.value.city).charAt(0).toUpperCase();
    const index = indexList.value.findIndex((son) => son === letter);

    nextTick(() => {
      listRef.value.setValueForTouch(index);
    });
  }
}

function handleTree(tree) {
  const result = [];
  const groupedCities = {};
  for (const parent of tree) {
    if (parent.children && parent.children.length) {
      for (const son of parent.children) {
        const letter = pinyin.getFullChars(son.name).charAt(0).toUpperCase();
        result.push({
          provinceCode: parent.code,
          province: parent.name,
          cityCode: son.code,
          city: son.name,
          letter: letter
        });
      }
    }
  }

  flatCityArr.value = result;
  commonStore.setCityList(result);
  getHotCity();

  for (const item of result) {
    if (/[A-Z]/.test(item.letter)) {
      if (!groupedCities[item.letter]) {
        groupedCities[item.letter] = [];
      }
      groupedCities[item.letter].push(item);
    }
  }
  return groupedCities;
}

// 获取热门城市
function getHotCity() {
  const hot = [110100, 310100, 440100, 440300, 330100, 330200, 370200, 330700];
  for (const item of flatCityArr.value) {
    if (hot.includes(item.cityCode)) {
      hotCityArr.value.push(item);
    }
  }
}

function goSearch() {
  uni.navigateTo({
    url: '/pages/common/searchCity'
  });
}

function handleClick(item) {
  if (types.value === 1) {
    // 单选
    const selectCityData = {
      provinceCode: item.provinceCode,
      province: item.province,
      cityCode: item.cityCode,
      city: item.city
    };
    uni.setStorageSync('selectCity', selectCityData);
    uni.$emit('getSelectCityData', selectCityData);
    back();
  }
}

function back() {
  uni.navigateBack();
}

onLoad((options) => {
  types.value = options?.type || 1;
  const c_storage = uni.getStorageSync('selectCity');
  if (c_storage) {
    modelForm.value.provinceCode = c_storage.provinceCode;
    modelForm.value.province = c_storage.province;
    modelForm.value.cityCode = c_storage.cityCode;
    modelForm.value.city = c_storage.city;
  }
  getCity();
});
</script>

<style lang="scss" scoped>
.city-item {
  min-width: 210rpx;
  height: 78rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #1c213e;
  margin-left: 16rpx;
  margin-bottom: 16rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  border: 2rpx solid transparent;
  box-sizing: border-box;
  &.active {
    color: $mt-color-primary;
    border-color: $mt-color-primary;
    background-color: rgba(20, 132, 238, 0.1);
  }
}
</style>
